package com.mindainfo.groundwave.server.base.dao.impl;

import com.mindainfo.groundwave.server.base.dao.IBaseDao;
import com.mongodb.WriteResult;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;

import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by MD-01 on 2017/5/15.
 */
public class BaseDaoImpl<T> implements IBaseDao<T>{

    private Class<T> entityClass;
    @Resource
    private Datastore datastore;


    public BaseDaoImpl() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class<T>) params[0];
    }

    /**
     * 保存实体
     */
    public int save(T t){
        Key<T> key = getDatastore().save(t);
        return Integer.parseInt(String.valueOf(key.getId()));
    }

    /**
     * 删除实体
     */
    public int delete(T t){
        WriteResult writeResult = getDatastore().delete(t);
        return writeResult.getN();
    }

    /**
     * 根据objectId查询
     */
    public T get(Integer id){
        return getDatastore().get(entityClass,id);
    }

    /**
     * 根据Id删除
     */
    public int delete(int id){
        return getDatastore().delete(entityClass,id).getN();
    }

    /**
     * 获得操作mongo的Datastore对象
     * @return
     */
    public Datastore getDatastore(){
        return datastore;
    }

    /**
     * 查询所有,根据id倒叙
     * @return
     */
    public List<T> all(){
        return getDatastore().createQuery(entityClass)
                .order("-id")
                .asList();
    }
}
